package GestionDeDatos;

import java.util.Iterator;
import java.util.ArrayList;
import java.util.Arrays;

import javax.xml.soap.SOAPElement;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPMessage;

public class ResultadoConsulta {

	private ArrayList<String> fields;
	private ArrayList< ArrayList<String> > registers;
	
	@SuppressWarnings("rawtypes")
	public ResultadoConsulta(SOAPMessage message) throws SOAPException {
		
		SOAPElement soapBodyElem = (SOAPElement)message.getSOAPBody().getChildElements().next();
		SOAPElement queryResultElem = (SOAPElement)soapBodyElem.getChildElements().next();
		
		Iterator iterator = queryResultElem.getChildElements();
		SOAPElement fieldsElem = (SOAPElement)iterator.next();
		SOAPElement registersElem = (SOAPElement)iterator.next();
		
		Iterator fieldsIterator = fieldsElem.getChildElements();
		Iterator registersIterator = registersElem.getChildElements();
		
		this.fields = new ArrayList<String>();
		while (fieldsIterator.hasNext()) {
			this.fields.add(((SOAPElement)fieldsIterator.next()).getValue());
		}
		
		this.registers = new ArrayList< ArrayList<String> >();
		while (registersIterator.hasNext()) {
			Iterator attributesIterator = ((SOAPElement)registersIterator.next()).getChildElements();
			
			ArrayList<String> attributes = new ArrayList<String>();
			while (attributesIterator.hasNext()) {
				attributes.add(((SOAPElement)attributesIterator.next()).getValue());
			}
			this.registers.add(attributes);
		}
	}
	
	public String[] getFields() {
		
		String[] fields = new String[] {};
		fields = this.fields.toArray(new String[this.fields.size()]);
		return fields;
	}
	
	public String[][] getRegisters() {
		
		String[][] registers = new String[this.registers.size()][];
		for (int i = 0; i < this.registers.size(); i++) {
		    registers[i] = this.registers.get(i).toArray(new String[this.registers.get(i).size()]);
		}
		return registers;
	}
	
	public String[][] getRegisters(String[] requiredFields) {
		
		Boolean fieldRequired[] = new Boolean[this.fields.size()];
		Arrays.fill(fieldRequired, false);
		for (int i = 0; i < requiredFields.length; i++) {
			if (this.fields.contains(requiredFields[i])) {
				fieldRequired[this.fields.indexOf(requiredFields[i])] = true;
			}
		}
		
		ArrayList< ArrayList<String> > registersAsArray = new ArrayList< ArrayList<String> >();
		for (int i = 0; i < this.registers.size(); i++) {
			ArrayList<String> attributes = new ArrayList<String>();
			for (int j = 0; j < this.fields.size(); j++) {
				if (fieldRequired[j]) attributes.add(this.registers.get(i).get(j));
			}
		    if (!registersAsArray.contains(attributes)) registersAsArray.add(attributes);
		}
		
		String[][] requiredRegisters = new String[registersAsArray.size()][];
		for (int i = 0; i < registersAsArray.size(); i++) {
			requiredRegisters[i] = registersAsArray.get(i).toArray(new String[registersAsArray.get(i).size()]);
		}
		
		return requiredRegisters;
	}
}
